package server;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: ChatServer
 * @DESCRIPT: TODO 服务端
 * @AUTHOR: lemontree
 * @DATA: 2020/8/28 3:31 PM
 **/
public class ChatServer {

     int port;

     List<Socket> clients;

     ServerSocket serverSocket;

     public static void main(String[] args){
         new ChatServer();
     }

    public ChatServer(){
        port = 9743;
        try {
            serverSocket = new ServerSocket(port);
            clients = new ArrayList<Socket>();
            System.out.println("服务器启动.......");
            //循环监听连接的客户端
            while(true){

                Socket socket = serverSocket.accept();
                clients.add(socket);
                ChatServerSendThread chatServerSendThread = new ChatServerSendThread(socket);
                Thread thread = new Thread(chatServerSendThread);
                thread.start();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    class ChatServerSendThread implements Runnable{
        Socket socket;
        private BufferedReader br;
        private PrintWriter pw;
        public String msg;

        public ChatServerSendThread(Socket s){
            socket = s;
        }

        public void run() {
            try {
                br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                msg = "欢迎【" + socket.getInetAddress() + "】进入聊天室！当前聊天室有【"
                        + clients.size() + "】人";

                sendMsg();

                while ((msg = br.readLine()) != null) {

                    msg = "【" + socket.getInetAddress() + "】说：" + msg;
                    sendMsg();

                }
            } catch (Exception ex) {

            }
        }

        public void sendMsg() {
            try {
                System.out.println(msg);

                for (int i = clients.size() - 1; i >= 0; i--) {
                    pw = new PrintWriter(clients.get(i).getOutputStream(), true);
                    pw.println(msg);
                    pw.flush();
                }
            } catch (Exception ex) {
            }
        }
    }
}



